package com.rjwh.dingdong.client.util;

import android.support.annotation.NonNull;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import rx.Observable;
import rx.subjects.PublishSubject;
import rx.subjects.Subject;

/**
 * 项目名称：whrjwh-parent
 * 类描述：
 * 创建人：wby
 * 创建时间：2016/6/27 14:30
 * 修改人：wby
 * 修改时间：2016/6/27 14:30
 * 修改备注：
 */
public class RxBus {
    private static final String TAG = RxBus.class.getSimpleName();
    private static RxBus instance;
    public static boolean DEBUG = false;
    private ConcurrentHashMap<Object, List<Subject>> subjectMapper = new ConcurrentHashMap<>();

    public static synchronized RxBus get() {
        if (null == instance) {
            instance = new RxBus();
        }
        return instance;
    }

    private RxBus() {
    }


    @SuppressWarnings("unchecked")
    public <T> Observable<T> register(@NonNull Object tag, @NonNull Class<T> clazz) {
        synchronized (subjectMapper) {
            List<Subject> subjectList = subjectMapper.get(tag);
            if (null == subjectList) {
                subjectList = new ArrayList<>();
                subjectMapper.put(tag, subjectList);
            }

            Subject<T, T> subject;
            subjectList.add(subject = PublishSubject.create());
            if (DEBUG) Log.d(TAG, "[register]subjectMapper: " + subjectMapper);
            return subject;
        }
    }

    public void unregister(@NonNull Object tag, @NonNull Observable observable) {
        synchronized (subjectMapper) {
            List<Subject> subjects = subjectMapper.get(tag);
            if (null != subjects) {
                subjects.remove((Subject) observable);
                if (subjects.size() == 0) {
                    subjectMapper.remove(tag);
                }
            }
            if (DEBUG) Log.d(TAG, "[unregister]subjectMapper: " + subjectMapper);
        }
    }

    public void post(@NonNull Object content) {
        post(content.getClass().getName(), content);
    }

    @SuppressWarnings("unchecked")
    public void post(@NonNull Object tag, @NonNull final Object content) {
        synchronized (subjectMapper) {
            List<Subject> subjectList = subjectMapper.get(tag);
            if (null != subjectList) {
                for (final Subject subject : subjectList) {
                    try {
                        subject.onNext(content);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            if (DEBUG) Log.d(TAG, "[send]subjectMapper: " + subjectMapper);
        }
    }

}
